#!/bin/bash

CURRENT_USER="$1"
# CURRENT_PATH means where the add_sudo.sh can be found.
CURRENT_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
SELF_SCRIPT="${CURRENT_PATH}/add_sudo.sh"



if [ -z "$1" ];then
    echo "Useage: $SELF_SCRIPT [user],example:sudo $SELF_SCRIPT [install_user]"
    exit 1
else
    id ${CURRENT_USER} >& /dev/null
    if [ $? -ne 0 ];then
        echo "The entered user does not exist. Exit"
        exit 1
    fi
fi

chmod o+x /etc/sudoers.d  > /dev/null 2>&1
CONFIG_FILE="/etc/sudoers.d/${CURRENT_USER}_specific"
if [ -f "${CONFIG_FILE}" ];then
    rm ${CONFIG_FILE}
fi


ALIAS=$(echo ${CURRENT_USER} | tr "[:lower:]" "[:upper:]" | tr -c "[:alnum:]" '_')

cat << EOF > ${CONFIG_FILE}
Cmnd_Alias COMMANDS_${ALIAS} = $(which apt-get), \\
                          $(which unsquashfs), \\
                          $(which echo), \\
                          $(which chroot), \\
                          $(which chmod), \\
                          $(which mkdir), \\
                          $(which ln), \\
                          $(which cat), \\
                          $(which rm), \\
                          $(which mv), \\
                          $(which sed), \\
                          $(which cp), \\
                          $(which umount), \\
                          $(which mount), \\
                          $(which fdisk), \\
                          $(which mkfs.ext3), \\
                          $(which partprobe), \\
                          $(which service), \\
                          /etc/init.d/networking, \\
                          $(which ifdown), \\
                          $(which ifup), \\
                          $(which ifconfig)


${CURRENT_USER}  ALL=(ALL:ALL)  NOPASSWD:SETENV:COMMANDS_${ALIAS}
EOF

sudo -n true || echo "Please check and fix the error line of the ${CONFIG_FILE} !"

echo "add sudo right for ${CURRENT_USER} successfully"
